<?php

namespace App\Console\Commands;

use App\Models\ElectricElectricity;
use App\Models\MqttModel;
use Illuminate\Console\Command;

class OperatingEquipment extends Command
{
    protected $signature = 'operating_equipment
                        {electric_code}
                        {handle}
                        {device_type}
                        {collect_id}';

    protected $description = '远程操作设备';

    /**
     * 2021/3/17--17:09
     * @effect:
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:handle
     */
    public function handle(): void
    {
        [$args, $str] = $this->assemble();
        try {
            $result = (new MqttModel())->sendToDevice($str, "server/{$args['collect_id']}");
            $this->info(json_encode($result, JSON_UNESCAPED_UNICODE));
        } catch (\Exception $e) {
            $this->error(json_encode(['code' => '100', 'msg' => $e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 拼装数据
     * @return array
     */
    protected function assemble(): ?array
    {
        $args = $this->arguments();
        $ele_exit = ElectricElectricity::where(['tableAddress' => $args['electric_code']])->count();
        if ($ele_exit == 0) {
            $arr = ['code' => 100, 'msg' => '表地址所代表电表设备不存在'];
            $this->error(json_encode($arr, JSON_UNESCAPED_UNICODE));
        } else {
            if (!in_array($args['handle'], ['on', 'off'])) {
                $arr1 = ['code' => 100, 'msg' => '请发送正确操作指令：on/off'];
                $this->error(json_encode($arr1, JSON_UNESCAPED_UNICODE));
            } else {
                // 指令输出
                $str = [
                    'sync' => 'true',//同步标识
                    'syncId' => 'server/9999',//同步消息号
                    'ver' => 1,//消息版本号
                    'id' => $args['electric_code'],//表号
                    'devVer' => 2,//设备版本号
                    'type' => 3,//消息类型
                    'data' => [
                        'handle' => $args['handle'],
                        'device_type' => $args['device_type'],//设备类型·：1，电表；2，水表
                        'update_time' => date('Y-m-d H:i:s'),
                    ]//数据区
                ];
                return array($args, $str);
            }

        }

    }
}
